package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private CartService cartService;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public void submit(Order order) {
        // 1.获取登录人user对象
        User user = UserHolder.get();
        // 1.1 判断 登录人是否为空
        if (user == null) {
            throw new CustomException("登录人不能为空");
        }
        //2.根据id查询address对象(根据id查询收货地址)
        Address address = addressMapper.selectById(order.getAddressId());
        // 2.1 判空
        if (address == null) {
            throw new CustomException("收货地址不能为空");
        }
        //3.获取购物车列表
        List<Cart> cartList = cartService.list();
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException("购物车不能为空");
        }

        // 通过mp生成订单id
        long orderId = IdWorker.getId();

        // 定金金额
        BigDecimal amount = new BigDecimal(0);

        //4.遍历购物车
        for (Cart cart : cartList) {
            // 封装订单
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName()); // 菜品或套餐名称
            orderDetail.setOrderId(orderId); // 订单id
            orderDetail.setDishId(cart.getDishId()); // 菜品id
            orderDetail.setSetmealId(cart.getSetmealId()); //套餐id
            orderDetail.setDishFlavor(cart.getDishFlavor()); // 口味
            orderDetail.setNumber(cart.getNumber()); // 数量
            orderDetail.setAmount(cart.getAmount()); // 金额
            orderDetail.setImage(cart.getImage());//图片
            //mapper保存
            orderDetailMapper.insert(orderDetail);

            //累加
            amount = amount.add(cart.getAmount()).multiply(new BigDecimal(cart.getNumber()));
        }
        // 5.保存订单
        // 5.1 封装
        order.setId(orderId); // 订单id
        order.setNumber(String.valueOf(orderId)); //订单号
        order.setStatus(1); //待付款
        order.setUserId(user.getId());//下单用户
        order.setOrderTime(new Date());//下单时间
        order.setCheckoutTime(new Date());// 结账时间
        order.setAmount(amount); //实收金额
        order.setUserName(user.getName());//下单人用户名
        order.setPhone(address.getDetail());// 收货人手机号
        order.setAddress(address.getDetail());// 收货人地址
        order.setConsignee(address.getConsignee()); // 收货人姓名
        // 5.2 mapper保存
        orderMapper.insert(order);

        //6.清空购物车
        cartService.clean();
    }

    //订单明细
    @Override
    public Page<Order> findByPage(Integer pageNum, Integer pageSize, String number, Date beginTime, Date endTime) {
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.like(number != null, Order::getNumber, number);
        qw.ge(beginTime != null, Order::getOrderTime, beginTime);
        qw.le(endTime != null, Order::getOrderTime, endTime);
        //开启分页
        Page<Order> orderPage = new Page<>(pageNum, pageSize);
        //分页查询
        Page<Order> page = orderMapper.selectPage(orderPage, qw);
        //遍历订单列表
        /*List<Order> orderList = page.getRecords();
        for (Order order : orderList) {
            //根据number查询订单
            LambdaQueryWrapper<OrderDetail> oqw = new LambdaQueryWrapper<>();
            oqw.eq(OrderDetail::getNumber,order.getNumber());
            //查询
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(oqw);
            //封装订单列表
            order.setNumber(orderDetailList.toString());
        }*/
        return page;
    }

    //历史订单
    @Override
    public Page<Order> findList(Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.eq(Order::getUserId, UserHolder.get().getId());
        //3. 设置排序(时间倒序)
        qw.orderByDesc(Order::getOrderTime);
        //开启分页
        Page<Order> page = new Page<>(pageNum, pageSize);
        //分页查询
        Page<Order> page1 = orderMapper.selectPage(page, qw);

        //获取订单列表
        List<Order> orderList = page1.getRecords();
        //遍历订单列表,回去订单明细
        for (Order order : orderList) {
            //根据订单获获取订单明细
            LambdaQueryWrapper<OrderDetail> oqw = new LambdaQueryWrapper<>();
            oqw.eq(OrderDetail::getOrderId, order.getId());
            //调用mapper查询
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(oqw);
            order.setOrderDetails(orderDetails);
        }
        return page;
    }


}
